using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using WB.Mvc.Forms;

namespace WB.Mvc.Demo
{
	public class FormFactory
	{
		static FormFactory()
		{
			Current = new FormFactory();
			Current.Register(new ModelFormCreationStrategy());
		}

		public IList<IFormCreationStrategy> StrategyPipeline =
			new List<IFormCreationStrategy>();

		public static FormFactory Current { get; set; }

		public FormBase Resolve(Type type)
		{
			return Resolve(type, null);
		}

		/// <summary>
		/// Resolve a form using the strategy pipeline of this instance of <see cref="FormFactory"/>.
		/// </summary>
		/// <param name="type">The type of the model.</param>
		/// <param name="form">Values for fields of the form.</param>
		public FormBase Resolve(Type type, NameValueCollection form)
		{
			foreach (var strategy in StrategyPipeline)
			{
				var result = strategy.Execute(type, form);
				if (result != null)
					return result;
			}

			throw new ResolveException(type);
		}

		public FormBase Resolve<T>(NameValueCollection form)
		{
			return Resolve(typeof (T), form);
		}

		public FormFactory Register(IFormCreationStrategy strategy)
		{
			StrategyPipeline.Add(strategy);
			return this;
		}
	}

	public class ResolveException : Exception
	{
		public ResolveException(Type type) : base(string.Format("Could not resolve for type {0}", type))
		{
		}
	}
}